package com.jt.service.impl;

import com.jt.dao.MenuMapper;
import com.jt.pojo.Menu;
import com.jt.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;


@Service
public class AopCacheMenuServiceImpl implements MenuService {

    private static Logger log =
            LoggerFactory.getLogger(AopCacheMenuServiceImpl.class);
    @Autowired
    private MenuMapper menuMapper;

    /**
     * @Cahceable 由此注解描述的方法为切入点方法, 此方法执行时, 底层会通过AOP
     * 机制先从缓存取数据,缓存有则直接返回,缓存没有则查数据,最后将查询的数据
     * 还会向redis存储一份
     * @param id
     * @return
     */
    //数据可以存储到缓存,
    @Cacheable(value = "menuCache",key = "#id")
    @Override
    public Menu selectById(Long id) {
        return menuMapper.selectById(id);
    }

    /**
     * @CachePut  缓存切入点方法
     * 注解的意思是更新缓存
     * @param menu
     * @return
     */
    @CachePut(value = "menuCache",key="#menu.id")
    @Override
    public Menu insertMenu(Menu menu) {
        log.info("insert before {} "+menu);
        menuMapper.insert(menu);
        log.info("insert after {} "+menu);
        return menu;
    }

    @CachePut(value = "menuCache",key="#menu.id")
    @Override
    public Menu updateMenu(Menu menu) {
        menuMapper.updateById(menu);
        return menu;
    }
}
